<template>
  <div>
    <el-tree
      ref="authTree"
      :data="menuTree"
      show-checkbox
      node-key="menuId"
      :default-expand-all="false"
      :props="defaultProps">
    </el-tree>
    <div style="text-align: center;margin-top: 5px">
      <el-button type="primary" @click="saveRoleMenu">分配权限</el-button>
    </div>
  </div>
</template>

<script>
import sysMenuApi from "@/api/system/sysMenu";
import sysRoleApi from "@/api/system/sysRole";

export default {
  name: "sys-role-select-menu",
  props: {
    activeId: {
      type: Number,
      default: null
    }
  },
  watch: {
    activeId: {
      immediate: true,
      handler: function (newVal, oldVal) {
        this.getCurrentRoleHasMenuIds(newVal)
      }
    }
  },
  data() {
    return {
      //树的节点和后台JSON的映射
      defaultProps: {
        children: "children",
        label: "menuName"
      },
      //树的数据
      menuTree: []
    }
  },
  created() {
    //加载所有的菜单的数据
    this.getMenuTreeList();
  },
  methods: {
    //加载所有菜单的数据
    getMenuTreeList() {
      sysMenuApi.listMenu().then(res => {
        this.menuTree = res.data
      })
    },
    //根据角色ID查询当前角色拥有的菜单权限
    getCurrentRoleHasMenuIds(roleId) {
      sysRoleApi.getCurrentRoleHasMenuIdsByRoleId(roleId).then(res => {
        this.$refs.authTree.setCheckedKeys(res.data);
      })
    },
    //保存角色和菜单关系
    saveRoleMenu() {
      //得到所有选中的keys
      const checkKeys = this.$refs.authTree.getCheckedKeys();
      //得到所有半选的keys
      const halfCheckKeys = this.$refs.authTree.getHalfCheckedKeys();
      //合并选中的数据
      checkKeys.push(...halfCheckKeys);
      sysRoleApi.saveRoleMenu(this.activeId, checkKeys).then(res => {
        this.$message.success(res.msg)
      })
    }
  }
}
</script>

<style scoped>

</style>
